<template>
  <div class="music-player">
    <!-- 歌曲信息 -->
    <div class="music-info">
      <el-avatar
        class="img"
        v-if="currentMusic == undefined"
        shape="square"
        :size="50"
        :src="musicIcon"
      ></el-avatar>
      <router-link v-if="currentMusic != undefined" to="/music-playerdetail">
        <el-avatar class="img" shape="square" :size="50" :src="musicIcon + '?param=50y50'"></el-avatar>
      </router-link>
      <div class="name-author">
        <div class="name-like">
          <router-link class="musicname" to="/music-playerdetail">{{musicName}}</router-link>
          <div v-show="isLogin" @click="musicLike" class="musicisLike">
            <span v-show="musicisLike" class="iconfont icon-heart-fill"></span>
            <span v-show="!musicisLike" class="iconfont icon-heart"></span>
          </div>
        </div>
        <!-- 歌手名字，跳转歌手页面 -->
        <div class="author-group">
          <div
            v-for="(name,index) of musicauthor"
            @click="$router.push({ name: 'artistAccount', query: { id:name.id } });"
            :key="index+'name.id'"
            class="author"
          >{{name.name}}</div>
        </div>
      </div>
    </div>

    <!-- 歌曲信息结束 -->
    <!-- 进度条栏位 -->
    <div class="music-progress-bar">
      <!-- 按钮 -->
      <div disabled class="music-progress-bar-btn">
        <span @click="backMusic" class="iconfont icon-player-skip-back"></span>
        <div :class="{'btn_disabled':musicUrl == ''}" @click="PlayPausemusic" class="play-btn">
          <span v-show="!musicisPlay" class="iconfont icon-palyer-start-01"></span>
          <span v-show="musicisPlay" class="iconfont icon-player-pause-01"></span>
        </div>
        <span @click="nextMusic" class="iconfont icon-player-skip-forward"></span>
      </div>
      <!-- 进度条 -->
      <div class="time-progress-all">
        <span class="current-time">{{musiccurrentTime|musictimeFormat}}</span>
        <div class="time-progress">
          <el-slider
            @change="changeCurrentTime"
            :disabled="musicUrl ==''"
            v-model="currentTime"
            :show-tooltip="false"
          ></el-slider>
        </div>
        <span class="all-time">{{musicTotalTime|musictimeFormat}}</span>
      </div>
    </div>
    <!-- 进度条结束 -->
    <!-- 右侧音量键，音乐列表 -->
    <div class="music-list-sound">
      <span @click="download" class="el-icon-download"></span>
      <el-tooltip popper-class="vocie-choose" placement="top" effect="light">
        <el-slider
          @change="changevoice"
          slot="content"
          class="sound-choose"
          v-model="voice"
          vertical
          height="150px"
        ></el-slider>
        <div class="musicsound" @click="MuteVoice">
          <span v-show="voice!=0" class="iconfont icon-musicfill"></span>
          <span v-show="voice == 0" class="iconfont icon-musicforbidfill"></span>
        </div>
      </el-tooltip>
      <span @click="drawer = true" class="iconfont icon-player-list-play"></span>
      <!-- 侧边栏，负责控制音乐列表 -->
      <el-drawer title="当前播放" append-to-body :visible.sync="drawer">
        <div style="display:flex; justify-content: space-between;">
          <div class="songlist" style="margin-left:20px;margin-bottom:20px">共{{ songsconut}}首</div>
          <a
            class="clearlist"
            style="margin-right:30px; text-decoration: none;color: rgb(125, 194, 255);"
            @click="clearlist"
            href="javascript:void(0)"
          >清空列表</a>
        </div>

        <el-table
          @current-change="handleCurrentChange"
          class="customer-no-border-table"
          :data="playmusicList"
          style="width: 100%;"
          stripe
          border
          :default-sort="{prop: 'playmusicList', order: 'descending'}"
        >
          <el-table-column width="260" prop="name" label="标题" sortable></el-table-column>
          <el-table-column width="220" label="歌手" sortable>
            <template v-slot="{row}">
              <div class="authors">
                <div
                  v-for="(item,index) of musicauthorbyfn(row)"
                  :key="index+'name'"
                  @click.stop="$router.push({ name: 'artistAccount', query: { id:item.id } });"
                  class="author"
                >{{item.name}}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="dt" width="80" label="时间" sortable>
            <template v-slot="{ row }">{{ (row.dt / 1000) | timeFormat }}</template>
          </el-table-column>
        </el-table>
      </el-drawer>
    </div>
    <!-- 右侧音量键，音乐列表结束 autoplay -->
    <audio ref="audioref" @ended="nextMusic" @timeupdate="updateCurrentTime" :src="musicUrl"></audio>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { downloadmusic } from "@/utils/downloadmusic.js";
import { mapState } from "vuex";
export default {
  name: "music-player",
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data () {
    //这里存放数据
    return {
      // 判断是否喜欢该音乐
      musicisLike: false,
      // 当前音乐时间轴,0-100用于判断进度条
      currentTime: 0,
      // // 当前音乐时间
      // currentTimesecond: 0,
      // 控制音量
      voice: 50,
      nowVoice: 50,
      //控制侧边歌曲数目栏位
      drawer: false,
    };
  },
  //计算属性 类似于data概念
  computed: {
    // 计算音乐进度格式
    musiccurrentTime () {
      if (this.currentMusic) {
        let time = this.$store.state.currentTimesecond * 1000;
        return time;
      } else {
        return 0;
      }
    },
    musicTotalTime () {
      if (this.currentMusic) {
        return this.currentMusic.dt;
      } else {
        return 0;
      }
    },
    // 获取音乐数量
    songsconut: function () {
      return this.$store.state.playmusicList.length;
    },
    //    当前播放音乐  当前播放歌单    当前音乐url   当前音乐index 音乐播放状态（按钮） 当前音乐时间
    ...mapState([
      "currentMusic",
      "playmusicList",
      "currentMusicUrl",
      "currentIndex",
      "musicisPlay",
      "currentTimesecond",
      "isLogin",
    ]),
    musicUrl: function () {
      if (this.currentMusic) {
        if (this.currentMusicUrl.code !== 200) {
          this.$message.error("播放失败");
        }
        if (!this.currentMusicUrl.data[0].url) {
          const h = this.$createElement;
          this.$notify({
            title: "当前歌曲暂无音源",
            message: h(
              "i",
              { style: "color: teal" },
              "因版权方要求，该资源暂时无法播放，我们正在争取歌曲回归"
            ),
          });
          return "";
        }
        return this.currentMusicUrl.data[0].url;
      } else {
        return "";
      }
    },
    musicIcon () {
      if (this.currentMusic) {
        return this.currentMusic.al.picUrl;
      } else {
        return "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png";
      }
    },
    musicName () {
      if (this.currentMusic) {
        return this.currentMusic.name;
      } else {
        return "未知歌曲";
      }
    },
    // 获取音乐作者
    musicauthor () {
      if (this.currentMusic) {
        if (this.currentMusic.ar) {
          let name = [];
          this.currentMusic.ar.forEach((element) => {
            name.push(element);
          });
          return name;
        }
        return "作者";
      } else {
        return "作者";
      }
    },
  },
  //监控data中的数据变化
  watch: {
    "$store.state.currentMusic": {
      handler () {
        this.$store.state.musicisPlay = true;
        // 渲染结束后播放音乐
        this.$nextTick(() => {
          this.$refs.audioref.play();
        });
      },
    },
  },
  //方法集合
  methods: {
    download () {
      if (this.musicUrl == "") {
        return;
      }

      downloadmusic(this.musicUrl, this.musicName);
    },
    // element组件，获取点击的音乐的信息
    handleCurrentChange (val) {
      // 把播放状态转为正在播放
      this.$store.state.musicisPlay = true;
      // 提交数据到vuex，通过vuex把数据传递给播放组件
      this.$store.commit("getcurrentIndex", val);
      this.$store.dispatch("getMusicDetail", val);
    },
    // 音乐开始暂停键
    PlayPausemusic () {
      if (this.musicUrl != "") {
        this.$store.state.musicisPlay = !this.$store.state.musicisPlay;
        if (!this.$store.state.musicisPlay) {
          this.$refs.audioref.pause();
        } else if (this.$store.state.musicisPlay) {
          this.$refs.audioref.play();
        }
      } else {
        console.log("暂无音乐");
      }
    },
    //根据音量进度条改变音量
    changevoice (val) {
      this.$refs.audioref.volume = val / 100;
    },
    // 是否喜爱歌曲
    musicLike () {
      this.musicisLike = !this.musicisLike;
      if (this.music == true) {
        // likemusicAPI();
      }
    },
    // 是否静音
    MuteVoice () {
      if (this.voice != 0) {
        this.nowVoice = this.voice;
        this.voice = 0;
        this.$refs.audioref.volume = this.voice / 100;
      } else if (this.voice == 0) {
        this.voice = this.nowVoice;
        this.$refs.audioref.volume = this.voice / 100;
      }
    },
    // 更新当前音乐时间轴
    updateCurrentTime () {
      if (!this.$refs.audioref) {
        return;
      }
      let time = this.$refs.audioref.currentTime;
      time = Math.floor(time);
      this.$store.state.currentTimesecond = this.$refs.audioref.currentTime;
      //判断歌曲时间
      if (time != this.currentTime) {
        let percent =
          (this.$refs.audioref.currentTime / (this.currentMusic.dt / 1000)) *
          100;
        this.currentTime = percent;
      }
    },
    // 通过组件更改音乐时间轴
    changeCurrentTime (val) {
      let currenttime = this.currentMusic.dt;
      let time = ((val / 100) * currenttime) / 1000;
      this.$refs.audioref.currentTime = time;
    },
    // 前近后退按钮
    backMusic () {
      this.$store.state.musicisPlay = true;
      this.$store.commit("setCurrentIndex", "back");
    },
    nextMusic () {
      this.$store.state.musicisPlay = true;
      this.$store.commit("setCurrentIndex", "next");
    },
    // 清除所有列表与歌曲
    clearlist () {
      this.$store.commit("clearAll");
    },
    // 获取音乐作者
    musicauthorbyfn (currentMusic) {
      if (currentMusic) {
        if (currentMusic.ar) {
          let name = [];
          currentMusic.ar.forEach((element) => {
            name.push(element);
          });
          return name;
        }
        return "作者";
      } else {
        return "作者";
      }
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created () { },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    this.$store.dispatch("getMusicDetail", this.currentMusic);
  },
  beforeCreate () { }, //生命周期 - 创建之前
  beforeMount () { }, //生命周期 - 挂载之前
  beforeUpdate () { }, //生命周期 - 更新之前
  updated () { }, //生命周期 - 更新之后
  beforeDestroy () { }, //生命周期 - 销毁之前
  destroyed () { }, //生命周期 - 销毁完成
  activated () { }, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped lang="less">
/deep/ .vocie-choose {
  border: 1px solid white;
  z-index: 500;
}
.music-player {
  background-color: white;
  border-top: 1px solid rgb(216, 216, 216);
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  height: 80px;
  z-index: 400;
  display: flex;
  justify-content: space-between;
  min-width: 1300px;
  // 歌曲信息栏位
  .music-info {
    margin-top: 15px;
    margin-left: 15px;
    width: 360px;
    display: flex;
    .img {
      flex-shrink: 0;
    }
    .name-author {
      display: flex;
      flex-wrap: wrap;
      height: 50px;

      .name-like {
        display: flex;
        height: 25px;
        width: 260px;

        .musicname {
          text-decoration: none;
          color: #373737;
          margin-left: 15px;
          cursor: pointer;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
        .musicname:hover {
          color: black;
        }

        .musicisLike {
          flex-shrink: 0;
          margin-left: 5px;
          .icon-heart {
            font-size: 23px;
            color: rgb(163, 163, 163);
            cursor: pointer;
          }
          .icon-heart-fill {
            font-size: 23px;
            color: red;
            cursor: pointer;
          }
        }
      }
      .author-group {
        display: flex;
        height: 25px;
        width: 260px;
        margin-top: 0;
        .author {
          margin-left: 15px;
          cursor: pointer;
        }
      }
    }
  }
  // 进度条
  .music-progress-bar {
    width: 400px;
    // 进度条
    .time-progress-all {
      position: relative;
      display: flex;
      .time-progress {
        margin-top: -5px;
        width: 400px;
      }
    }
    .current-time {
      position: absolute;
      left: -60px;
      color: #727272;
    }
    .all-time {
      position: absolute;
      right: -60px;
      color: #727272;
    }

    /deep/ .el-slider__runway {
      height: 3px;

      .el-slider__bar {
        background-color: rgb(122, 211, 252);
        height: 3px;
      }
    }
    /deep/ .el-slider__button {
      background-color: rgb(122, 211, 252);
      width: 8px;
      height: 8px;
      border-radius: 50%;
      transition: 0.2s;
      user-select: none;
      border: 0px;
    }
    /deep/ .el-slider__button-wrapper {
      top: -17px;
    }
    // 按钮
    .music-progress-bar-btn {
      display: flex;
      margin-top: 10px;
      justify-content: center;

      .icon-player-skip-back {
        margin-top: 8px;
        font-size: 23px;
        margin-right: 40px;
        color: #4d4d4d;
        cursor: pointer;
      }
      .icon-player-skip-forward {
        margin-top: 8px;
        font-size: 23px;
        margin-left: 40px;
        color: #4d4d4d;
        cursor: pointer;
      }
      .icon-player-skip-back:hover {
        color: rgb(122, 211, 252);
      }
      .icon-player-skip-forward:hover {
        color: rgb(122, 211, 252);
      }
      .play-btn {
        height: 40px;
        width: 40px;
        border-radius: 20px;
        text-align: center;
        line-height: 40px;
        cursor: pointer;
        background-color: rgb(233, 233, 233);
        .icon-palyer-start-01 {
          padding-left: 5px;
          font-size: 30px;
          color: #4d4d4d;
        }
        .icon-player-pause-01 {
          font-size: 30px;
          border-radius: 20px;
          color: #4d4d4d;
        }
      }
      .btn_disabled {
        cursor: not-allowed;
      }
      .play-btn:hover {
        background-color: rgb(218, 218, 218);
      }
    }
  }

  // 右侧区域
  .music-list-sound {
    margin-top: 20px;
    margin-right: 20px;
    width: 360px;
    display: flex;
    justify-content: flex-end;
    .sound-choose {
      position: absolute;
      top: -170px;
      width: 20px;
      height: 180px;
      border: 1px solid black;
      background-color: white;
      border-radius: 5px;
      /deep/ .el-slider__runway {
        margin-top: 10px;
      }
    }

    .icon-musicfill {
      font-size: 35px;
      color: #4d4d4d;
      cursor: pointer;
    }

    .icon-musicforbidfill {
      font-size: 35px;
      color: #4d4d4d;
      cursor: pointer;
    }
    .el-icon-download {
      font-size: 35px;
      color: #4d4d4d;
      cursor: pointer;
      margin-right: 20px;
    }
    .icon-player-list-play {
      font-size: 35px;
      color: #4d4d4d;
      margin-left: 20px;
      cursor: pointer;
    }
  }
}
.authors {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  .author {
    display: inline-block;
    cursor: pointer;
    margin-right: 5px;
  }
}
// 去除elmentuitab自带的边框
/*去掉表格单元格边框*/
:deep(.customer-no-border-table th) {
  border: none;
}
/deep/ .customer-no-border-table td,
/deep/ .customer-no-border-table th.is-leaf {
  border: none;
}
/*表格最外边框*/
/deep/ .customer-no-border-table .el-table--border,
.el-table--group {
  border: none;
}
/*头部边框*/
/deep/ .customer-no-border-table thead tr th.is-leaf {
  border: 0px solid #ebeef5;
  border-right: none;
}
/deep/ .customer-no-border-table thead tr th:nth-last-of-type(2) {
  border-right: 0px solid #ebeef5;
}
/*表格最外层边框-底部边框*/
/deep/ .customer-no-border-table .el-table--border::after,
/deep/ .customer-no-border-table .el-table--group::after {
  width: 0;
}
/deep/ .customer-no-border-table::before {
  width: 0;
}
/deep/ .customer-no-border-table .el-table__fixed-right::before,
.el-table__fixed::before {
  width: 0;
}
/deep/ .customer-no-border-table .el-table__header tr th {
  background: #fff;
  color: #333333;
  padding: 3px;
  font-weight: 550;
  height: 36px;
  border: 0px;
  font-size: 15px;
}
/deep/.el-table::before {
  height: 0;
}
</style>
